package com.ssy.lingxi.message.websocket.session;

import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketSession;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * webSocketSession上下文
 * @author yzc
 * @version 2.0.0
 * @date 2020/11/2
 */
public class WsSessionContext {

    /**
     * key - session缓存
     */
    private final static ConcurrentHashMap<String, WebSocketSession> SESSION_MAP = new ConcurrentHashMap<>();

    /**
     * 保存session
     * @param key = source+memberId+roleId+userId
     * @param session
     */
    public static void add(String key, WebSocketSession session) {
        SESSION_MAP.put(key, session);
    }

    /**
     * 移除session
     * @param session
     */
    public static void remove(WebSocketSession session) {
        SESSION_MAP.values().removeIf(s -> s.equals(session));
    }

    /**
     * 获取session
     */
    public static WebSocketSession get(String key) {
        return SESSION_MAP.get(key);
    }

    /**
     * 匹配session
     */
    public static List<WebSocketSession> pattern(String key) {
        if (!StringUtils.hasLength(key)) {
            return Collections.emptyList();
        }

        String pattern = WsSessionKey.getPattern(key);
        if (!StringUtils.hasLength(pattern)) {
            return Collections.emptyList();
        }

        return SESSION_MAP.entrySet().stream().filter(e -> Pattern.matches(pattern, e.getKey())).map(Map.Entry::getValue).collect(Collectors.toList());
    }
}
